package org.xdj.blue.java.io.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xdj.blue.java.io.client.ClientSocket;

/**
 * 服务端业务处理线程
 * @author 91power—xdj
 *
 */
public class SocketHandle implements Runnable {

	public static Logger logger = LoggerFactory.getLogger(SocketHandle.class);
	private Socket socket;
	private BufferedReader reader;
	private PrintWriter writer;
	private StringBuilder request = new StringBuilder();
	private String response;

	public SocketHandle(Socket socket) {
		this.socket = socket;
	}

	public void run() {
		String req = "";
		try {
			writer = new PrintWriter(socket.getOutputStream(), true);
			reader = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			while (true) {
				logger.debug("--server-read--");
				req = reader.readLine();
				logger.debug("req:" + req);
				// 以"over"作为结束标识符
				if (null == req || req.equals("over")) {
					logger.debug("--数据为空跳出--");
					break;
				}
				//每行读取后数据做拼接
				request.append(req);
			}
			req=null;
			logger.debug("request:" + request);
			// 以"over"作为结束标识符并添加换行符，不然客户端输出流会持续读取。
			response = "I'm response from server!---"+new Date()+"\rover\r";
			writer.write(response);
			writer.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally{
			try {
                if(socket!=null)
                    socket.close();
                System.out.println("--连接关闭--");
            } catch (IOException e) {
                e.printStackTrace();
            }
		}

	}

}
